package com.ruoyi.feike.instener;

import com.github.pagehelper.util.StringUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.EmailUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.feike.domain.BasicInformation;
import com.ruoyi.feike.domain.ProposalByCommericalAndMarketing;
import com.ruoyi.feike.domain.ReportInsurance;
import com.ruoyi.feike.mapper.*;
import com.ruoyi.feike.service.IProposalByCommericalAndMarketingService;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.HistoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.delegate.Expression;
import org.activiti.engine.history.*;
import org.activiti.engine.task.Task;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.*;

@Slf4j
@Component
public class SendMailListener implements ExecutionListener , ApplicationContextAware {

    private Expression state;

    @Value("${spring.mail.from}") // 从application.yml配置文件中获取
    private String from; //  发送发邮箱地址

    @Value("${uat.url}") // 从application.yml配置文件中获取
    private String url; //  网址

    @Value("${uat.msg}") // 从application.yml配置文件中获取
    private String msg; //  网址

    @Value("${uat.isSendEmal}") // 从application.yml配置文件中获取
    private String isSendEmal; //  网址

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private BasicInformationMapper basicInformationMapper;

    @Autowired
    private AnnualReviewyMapper annualReviewyMapper;

    private static ApplicationContext context = null;

    @Override
    public void notify(DelegateExecution delegateExecution) {
        log.info("开始发办结邮件");
        String activeProfile = context.getEnvironment().getActiveProfiles()[0];
        if(activeProfile.equals("dev")){
            isSendEmal = "true";
            url = "http://localhost:81";
            from ="Service.IT@stellantisafc.com.cn";
            msg ="【UAT测试邮件】";
        }else if(activeProfile.equals("prod")){
            isSendEmal = "true";
            url = "http://10.226.185.146:81";
            from ="Service.IT@stellantisafc.com.cn";
            msg ="";
        }else if (activeProfile.equals("uat")){
            isSendEmal = "true";
            url = "http://10.226.186.143:82";
            from ="Service.IT@stellantisafc.com.cn";
            msg ="【UAT测试邮件】";
        }
        if(isSendEmal!=null && isSendEmal.equals("true")){
            String instanceId = delegateExecution.getProcessInstanceId();
            ArrayList<SysUser> users = new ArrayList<>();
            if(null !=instanceId) {
                HistoryService historyService = SpringUtils.getBean(HistoryService.class);
                ISysUserService userService = SpringUtils.getBean(ISysUserService.class);
                List<HistoricTaskInstance> taskInstance = historyService.createHistoricTaskInstanceQuery().processInstanceId(instanceId).list();
                HistoricProcessInstance procInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(instanceId).singleResult();
                String businessKey = procInstance.getBusinessKey();
                if(null != procInstance){
                    String startUserId = procInstance.getStartUserId();
                    SysUser sysUser = userService.selectUserById(Long.valueOf(startUserId));
                    if(sysUser != null && sysUser.getEmail()!=null){
                        users.add(sysUser);
                    }
                }
                for (HistoricTaskInstance his : taskInstance) {
                    if(his.getName()!=null && his.getAssignee()!=null && (his.getName().equals("保证金调整确认")
                    ||his.getName().equals("保险购买确认")||his.getName().equals("盈余保证金操作")
                            ||his.getName().equals("OP") ||his.getName().equals("OP1")
                            ||his.getName().equals("自发合同校验") ||his.getName().equals("自发合同审核")
                            ||his.getName().equals("自发合同-签回合同校验"))){
                        //这里拿到的是用户名
                        SysUser user = userService.selectUserByUserName(his.getAssignee());
                        if(user != null && user.getEmail()!=null){
                            users.add(user);
                            break;
                        }
                    }
                }
                for(SysUser user : users){
                    //发送邮件
                    sendMailByEmailInfo(user,businessKey);
                }
            }
        }
    }

    public void sendMailByEmailInfo(SysUser user,String instanceId) {
            try {
                AnnualReviewyMapper reviewyMapper = SpringUtils.getBean(AnnualReviewyMapper.class);
                String str = reviewyMapper.selectByInstanceId(instanceId);

                BasicInformationMapper informationMapper = SpringUtils.getBean(BasicInformationMapper.class);
                List<BasicInformation> basicInformations = informationMapper.selectDealerGroupByByInstanceId(instanceId);

                String names = "";
                for (BasicInformation basicInformation : basicInformations) {
                    if(StringUtils.isNotEmpty(basicInformation.getDealerNameCN())){
                        names += basicInformation.getDealerNameCN();
                        continue;
                    }
                }
                String ln = "<br>";
                String content = msg +  ln + "网站链接:"+ "<a href ='" + url + "'>点此登录</a>"+"|--------|申请流程名称："+str+"|----------|经销商名称: "+names;
                // 测试文本邮件发送（无附件）
                String to = user.getEmail();
                if(!StringUtil.isEmpty(to)){
                    System.out.println("发送办结任务到"+ to);
                    String title = "您有任务已办结";
                    //带附件方式调用
                    JavaMailSender bean = SpringUtils.getBean(JavaMailSender.class);
                    new EmailUtil(from, bean).sendMessageCarryFiles(to, title, content, null);
                    // return AjaxResult.success();
                }
            } catch (Exception e) {
               e.printStackTrace();
            }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }
}
